package com.spring.test.service.impl;

import com.spring.test.dao.RoleDao;
import com.spring.test.dao.UserDao;
import com.spring.test.dao.impl.RoleDaoImpl;
import com.spring.test.domain.Role;
import com.spring.test.domain.User;
import com.spring.test.service.UserService;
import org.springframework.dao.EmptyResultDataAccessException;

import java.util.List;

public class UserServiceImpl implements UserService {

    private UserDao dao;
    private RoleDao roleDao;

    public void setRoleDao(RoleDao roleDao) {
        this.roleDao = roleDao;
    }

    public void setDao(UserDao dao) {
        this.dao = dao;
    }

    @Override
    public List<User> list() {

        List<User> userList = dao.findAll();

        //封装userList中的每一个User的roles数据
        for (User user : userList) {

            //获得id
            Long id = user.getId();

            //将id作为参数 查询当前userid对应的role集合的数据
            List<Role> roles = roleDao.findRoleByUserId(id);

            user.setRoles(roles);

        }

        return userList;

    }

    @Override
    public void save(User user, Long[] roleIds) {

        //存入user
        Long userid = dao.save(user);

        //存入user_role
        dao.saveUserRoleRel(userid, roleIds);

    }

    @Override
    public void del(Long userId) {

        //删除sys_user_role
        dao.delUserRoleRel(userId);

        //删除sys_user
        dao.del(userId);

    }

    @Override
    public User login(String username, String password) {

        try {
            User user = dao.findByUsernameAndPassword(username, password);
            return user;
        } catch (EmptyResultDataAccessException c) {
            return null;
        }

    }

}
